package com.cn.aam.checaiduo.ui.homepage.adapter;

import android.content.Context;
import android.support.annotation.NonNull;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.alibaba.android.vlayout.DelegateAdapter;
import com.alibaba.android.vlayout.LayoutHelper;
import com.alibaba.android.vlayout.VirtualLayoutManager.LayoutParams;
import com.bigkoo.convenientbanner.ConvenientBanner;
import com.bigkoo.convenientbanner.holder.CBViewHolderCreator;
import com.bigkoo.convenientbanner.holder.Holder;
import com.bigkoo.convenientbanner.listener.OnItemClickListener;
import com.bumptech.glide.Glide;
import com.cn.aam.checaiduo.Const;
import com.cn.aam.checaiduo.R;
import com.cn.aam.checaiduo.base.BaseActivity;
import com.cn.aam.checaiduo.base.web.NormalWebActivity;
import com.cn.aam.checaiduo.bean.BannerB;
import com.cn.aam.checaiduo.bean.IndexB;
import com.cn.aam.checaiduo.ui.arouter.UIRouter;
import com.cn.aam.checaiduo.ui.arouter.section.RouterMore;
import com.cn.aam.checaiduo.ui.homepage.MainActivity;
import com.cn.aam.checaiduo.ui.me.AutoReservationActivity;
import com.cn.aam.checaiduo.ui.me.BeginnerParkActivity;
import com.cn.aam.checaiduo.ui.me.MessageListActivity;
import com.cn.aam.checaiduo.utils.GlideRoundTransform;
import com.cn.aam.checaiduo.utils.MyViewsUtils;
import com.cn.aam.checaiduo.utils.WindowsUtils;
import com.cn.aam.checaiduo.widget.MarqueTextView;
import com.cn.aam.checaiduo.widget.RandomTextView;

import java.math.BigDecimal;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import me.grantland.widget.AutofitHelper;

import static com.cn.aam.checaiduo.Const.INTENT_REQUEST_PARK;

/**
 * monker on 2017/5/23.
 */

public class HomeContentAdapter extends DelegateAdapter.Adapter<HomeContentAdapter.MainContentHolder> {

    private Context mContext;
    private LayoutHelper mLayoutHelper;

    private LayoutParams mLayoutParams;
    private int mCount = 0;

    private IndexB indexB;
    private List<BannerB> bannerList;
    private MainContentHolder mainContentHolder;


    public HomeContentAdapter(Context context, LayoutHelper layoutHelper, int count) {
        this(context, layoutHelper, count, new LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
    }

    public HomeContentAdapter(Context context, LayoutHelper layoutHelper, int count, @NonNull LayoutParams layoutParams) {
        this.mContext = context;
        this.mLayoutHelper = layoutHelper;
        this.mCount = count;
        this.mLayoutParams = layoutParams;
    }

    public void setBannerList(List<BannerB> bannerList) {
        this.bannerList = bannerList;
        notifyDataSetChanged();
    }

    public List<BannerB> getBannerList() {
        return bannerList;
    }


    public void setData(IndexB indexB) {
        this.indexB = indexB;
        notifyDataSetChanged();
    }

    public ConvenientBanner getBanner() {
        if (mainContentHolder != null)
            return mainContentHolder.convenientBanner;
        return null;
    }


    public void clearData() {
        this.indexB = null;
    }

    @Override
    public LayoutHelper onCreateLayoutHelper() {
        return mLayoutHelper;
    }

    @Override
    public MainContentHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View v = LayoutInflater.from(mContext).inflate(R.layout.item_homemain_content, parent, false);
        return new MainContentHolder(v);
    }

    @Override
    public void onBindViewHolder(MainContentHolder holder, int position) {
        holder.itemView.setLayoutParams(new LayoutParams(mLayoutParams));
    }


    @Override
    protected void onBindViewHolderWithOffset(MainContentHolder holder, int position, int offsetTotal) {
        mainContentHolder = holder;
        mainContentHolder.init();
    }


    @Override
    public int getItemCount() {
        return mCount;
    }


    public class MainContentHolder extends RecyclerView.ViewHolder {

        @BindView(R.id.home_ll_noLogin)
        LinearLayout homeLlNoLogin;
        @BindView(R.id.rtv)
        RandomTextView mRandomTextView;//排名
        @BindView(R.id.home_ll_hasLogin)
        LinearLayout homeLlHasLogin;

        @BindView(R.id.ll_notify)
        LinearLayout llNotify;
        @BindView(R.id.marqueeView)
        MarqueTextView marqueeView;

        @BindView(R.id.main_ll_rankParent)
        LinearLayout llRankParent;
        @BindView(R.id.main_ll_rank)
        LinearLayout llRank;
        @BindView(R.id.main_tv_realName)
        TextView name;
        @BindView(R.id.main_tv_profit)
        TextView profit;
        @BindView(R.id.main_tv_profit_tip)
        TextView profitTip;

        @BindView(R.id.banner_ad)
        ConvenientBanner convenientBanner;

        public MainContentHolder(View itemView) {
            super(itemView);
            ButterKnife.bind(this, itemView);

        }

        private void init() {

            if (indexB != null) {
                homeLlHasLogin.setVisibility(View.VISIBLE);
                homeLlNoLogin.setVisibility(View.GONE);
                llNotify.setVisibility(View.VISIBLE);
                AutofitHelper.create(profit);

                //是否投资
                if (TextUtils.equals(indexB.getInvesting_amount(), "0")) {
                    llRank.setVisibility(View.GONE);
                    llRankParent.setBackground(ContextCompat.getDrawable(mContext, R.drawable.ic_main_no_invest));
                    mRandomTextView.setVisibility(View.GONE);
                } else {
                    llRank.setVisibility(View.VISIBLE);
                    llRankParent.setBackground(null);
                    mRandomTextView.setVisibility(View.VISIBLE);
                }
                //是否实名认证
                if (TextUtils.equals(indexB.getAuth_status(), Const.AUTH_STATUS)) {
                    String realName = indexB.getReal_name();
                    if (realName.length() > 1) {
                        StringBuilder builder = new StringBuilder(realName);
                        builder.replace(1, 2, "*");
                        realName = builder.toString();
                    }
                    name.setText(realName);
                } else {
                    name.setText("先生/女士");
                }

                mRandomTextView.setText(resetRank());
                mRandomTextView.setPianyilian(RandomTextView.ALL);
                mRandomTextView.start();
                if (indexB.getProfit().contains("万")) {
                    profitTip.setText("累计收益(万元)");
                    indexB.setProfit(indexB.getProfit().replace("万", ""));
                } else {
                    profitTip.setText("累计收益(元)");
                }
                BigDecimal bd = new BigDecimal(indexB.getProfit());
                bd = bd.setScale(2, BigDecimal.ROUND_HALF_UP);
                profit.setText(bd.toString());
                MyViewsUtils.setMarqueeView(marqueeView, indexB.getNotify_title());


                marqueeView.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        mContext.startActivity(MessageListActivity.newInstance(mContext));
                    }
                });
            } else {
                homeLlHasLogin.setVisibility(View.GONE);
                homeLlNoLogin.setVisibility(View.VISIBLE);
                llNotify.setVisibility(View.GONE);
            }
            showBanner();
        }


        /**
         * @description显示轮播
         */
        public void showBanner() {

            if (bannerList == null || convenientBanner.isTurning()) return;
            convenientBanner.setPages(new CBViewHolderCreator<NetworkImageHolderView>() {
                @Override
                public NetworkImageHolderView createHolder() {
                    return new NetworkImageHolderView();
                }
            }, bannerList);

            convenientBanner.setPageIndicator(new int[]{R.drawable.ic_indicator, R.drawable.ic_indicator_focus});
            convenientBanner.setOnItemClickListener(new OnItemClickListener() {
                @Override
                public void onItemClick(int position) {
                    if (MyViewsUtils.isFastDoubleClick()) return;
                    BannerB item = bannerList.get(position);
                    String url = "";
                    if (TextUtils.isEmpty(item.getLink()))
                        return;

                    if (TextUtils.equals("BeginnerParkActivity", item.getLink())) {
                        ((MainActivity) mContext).startActivityForResult(BeginnerParkActivity.newInstance(mContext), INTENT_REQUEST_PARK);
                    } else if (TextUtils.equals("InvitePrizesActivity", item.getLink())) {
                        if (!((MainActivity) mContext).needLogin())
                            UIRouter.getInstance().openPage(mContext, UIRouter.ME.AC_INVITEPRIZES);
                    } else {
                        mContext.startActivity(NormalWebActivity.newInstance(mContext, item.getLink(), item.getTitle()));
                        return;
                    }
                    if (!TextUtils.isEmpty(item.getUrl())) {
                        mContext.startActivity(NormalWebActivity.newInstance(mContext, item.getUrl(), item.getTitle()));
                    }

                }
            });
            if (!convenientBanner.isTurning())
                convenientBanner.startTurning(3000);
        }

        class NetworkImageHolderView implements Holder<BannerB> {
            ImageView imageView;

            @Override
            public View createView(Context context) {
                ViewGroup content = (ViewGroup) LayoutInflater.from(context).inflate(R.layout.banner_item_home, null);
                imageView = content.findViewById(R.id.imageView);
                return content;
            }

            @Override
            public void UpdateUI(Context context, int position, BannerB data) {
                Glide.with(context)
                        .load(data.getBanner())
                        .centerCrop()
                        .transform(new GlideRoundTransform(mContext, 6))
                        .into(imageView);
            }
        }

        private String resetRank() {
            String rank = indexB.getRank();
            int length = rank.length();
            switch (length) {
                case 1:
                    rank = "0000" + rank;
                    break;
                case 2:
                    rank = "000" + rank;
                    break;
                case 3:
                    rank = "00" + rank;
                    break;
                case 4:
                    rank = "0" + rank;
                    break;
            }
            return rank;
        }

        @OnClick(R.id.home_tv_gotoRegister)
        void clickGoRegister() {
            if (MyViewsUtils.isFastDoubleClick()) return;
            ((MainActivity) mContext).goLogin();
        }

        @OnClick(R.id.home_rl_firstItem)
        void clickInvite() {//邀请有奖
            if (MyViewsUtils.isFastDoubleClick()) return;
            if (!((BaseActivity) mContext).needLogin())
                UIRouter.getInstance().openPage(mContext, UIRouter.ME.AC_INVITEPRIZES);
        }

        @OnClick(R.id.home_rl_secondItem)
        void clickSignIn() {//签到有奖
            if (MyViewsUtils.isFastDoubleClick()) return;
            if (!((BaseActivity) mContext).needLogin())
                UIRouter.getInstance().openPage(mContext, UIRouter.ME.AC_SIGNIN);
        }

        @OnClick(R.id.home_rl_thirdItem)
        void clickHelp() {//帮助中心
            if (MyViewsUtils.isFastDoubleClick()) return;
            UIRouter.getInstance().openPage(mContext, UIRouter.MORE.HELP_CENTER);
        }

        @OnClick(R.id.home_rl_fourItem)
        void clicGigt() {//预约投资
            if (MyViewsUtils.isFastDoubleClick()) return;
            if (!((BaseActivity) mContext).needLogin())
                mContext.startActivity(AutoReservationActivity.newInstance(mContext));

        }
    }
}
